<template>
	<div class="boxes-detail-performance">
		<div class="the-monitor-content">
			<div class="the-store-information">
				<div class="the-common-title">
					<global-svg-icon icon-name="config-title-tri" style="vertical-align: sub" width="3px" height="18px"></global-svg-icon
					><span class="text">存储信息</span>
				</div>
				<div class="the-information-content">
					<div class="information-detail">
						<div class="use-status">存储空间已使用</div>
						<div class="detail-percent">
							<span class="detail-percent-current">{{ diskData?.use }}</span> GB/{{ diskData?.total }}GB
						</div>
					</div>
					<a-progress :percent="diskData?.percent" :show-info="false"></a-progress>
				</div>
			</div>
			<div class="the-performance-monitor">
				<div class="the-common-title">
					<global-svg-icon style="vertical-align: sub" icon-name="config-title-tri" width="3px" height="18px"></global-svg-icon
					><span class="text">性能监控</span>
				</div>
				<div class="the-performance-content">
					<div class="the-content-child">
						<div class="the-child-title">CPU利用率</div>
						<div class="the-child-percent">{{ performancePercentData?.cpu }}<span class="the-percent-symbol">%</span></div>
						<div ref="cpu" class="the-child-chart"></div>
					</div>
					<div class="the-content-child">
						<div class="the-child-title">NPU利用率</div>
						<div class="the-child-percent">{{ performancePercentData?.npu }}<span class="the-percent-symbol">%</span></div>
						<div ref="npu" class="the-child-chart"></div>
					</div>
					<div class="the-content-child">
						<div class="the-child-title">内存利用率</div>
						<div class="the-child-percent">{{ performancePercentData?.memory }}<span class="the-percent-symbol">%</span></div>
						<div ref="memory" class="the-child-chart"></div>
					</div>
					<div class="the-content-child">
						<div class="the-child-title">网络速度</div>
						<div class="the-child-network">
							<div class="the-network-speed">
								<div class="speed-out-icon"></div>
								<div class="speed-title">上行</div>
								<div class="speed-number">{{ networkSpeed?.out }}</div>
								<div class="speed-symbol">{{ networkSpeed?.outSymbol }}</div>
							</div>
							<div class="the-network-speed">
								<div class="speed-in-icon"></div>
								<div class="speed-title">下行</div>
								<div class="speed-number">{{ networkSpeed?.in }}</div>
								<div class="speed-symbol">{{ networkSpeed?.inSymbol }}</div>
							</div>
						</div>
						<div ref="network" class="the-child-chart"></div>
					</div>
				</div>
			</div>
			<div class="logo">
				<img src="@/global-assets/imgs/banner.png" alt="" />
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { exceedAuthority } from '@/global-utils/base.utils';
import { BoxManageApi } from '../../../api';
import { appStore } from '@/global-store/index';

defineOptions({ name: 'BoxPerformance' });
const { WebSocketStore } = appStore;
const { SocketState } = WebSocketStore;
const route = useRoute();

const id = ref<string>('');
const boxSerial = ref<string>('');
// 盒子名称
const name = ref<string>('');
// 存储空间
let diskData = reactive<{
	percent?: number;
	free?: number;
	total: number;
	use: number;
}>({
	percent: 5,
	total: 0,
	use: 0
});
// CPU利用率 NPU利用率 内存利用率
interface networkData {
	in: { data: number; value: string };
	out: { data: number; value: string };
}
interface timeDate {
	time: string;
	data: networkData;
}
interface numberData {
	time: string;
	data: number;
}
let performanceData = reactive<{
	cpuQueue: numberData[];
	npuQueue: numberData[];
	memoryQueue: numberData[];
	networkQueue: timeDate[];
	diskQueue: any;
}>({
	cpuQueue: [],
	npuQueue: [],
	memoryQueue: [],
	networkQueue: [],
	diskQueue: []
});

let cpu = ref(HTMLDivElement);
let npu = ref(HTMLDivElement);
let network = ref(HTMLDivElement);
let memory = ref(HTMLDivElement);
const performancePercentData = reactive<{
	cpu: number;
	npu: number;
	memory: number;
	network: { out: string; in: string };
}>({
	cpu: 0,
	npu: 0,
	memory: 0,
	network: { out: '0kb', in: '0kb' }
});

// 网络速度
const networkSpeed = computed(() => {
	let res: any = {};
	const outStr = performancePercentData.network?.out;
	const outNum = outStr?.indexOf(' ');
	const inStr = performancePercentData.network?.in;
	const inNum = inStr?.indexOf(' ');
	res.out = outStr?.substring(0, outNum);
	res.outSymbol = outStr?.substring(outNum, outStr.length);
	res.in = inStr?.substring(0, inNum);
	res.inSymbol = inStr?.substring(inNum, inStr.length);
	return res;
});

let cpuChart: any, npuChart: any, networkChart: any, memoryChart: any;

const draw = (): void => {
	let option: any;
	option = {
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: [],
			axisTick: {
				show: false // 隐藏x轴刻度
			},
			splitLine: {
				show: true,
				lineStyle: {
					width: 0.5,
					color: '#2B3A50'
				}
			},
			axisLabel: {
				interval: 0
			}
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'line'
			},
			formatter: ''
		},
		yAxis: {
			type: 'value',
			axisLabel: {
				show: true,
				interval: 'auto',
				formatter: '{value}%'
			},
			splitLine: {
				show: true,
				lineStyle: {
					width: 0.5,
					color: '#2B3A50'
				}
			},
			axisTick: {
				show: false // 隐藏x轴刻度
			}
		},
		grid: {
			x: 40,
			y: 20,
			x2: 15,
			y2: 45,
			borderWidth: 1
		},
		series: [
			{
				data: [],
				type: 'line',
				value: [],
				areaStyle: {},
				smooth: true,
				symbol: 'none',
				lineStyle: { width: 3, color: '' }
			},
			{
				data: [],
				value: [],
				type: 'line',
				areaStyle: {},
				label: [],
				smooth: true,
				symbol: 'none',
				lineStyle: { width: 3, color: '' }
			},
			{
				data: [],
				value: [],
				type: 'line',
				areaStyle: {},
				label: [],
				smooth: true,
				symbol: 'none',
				lineStyle: { width: 3, color: '#000' }
			},
			{
				data: [],
				value: [],
				type: 'line',
				areaStyle: {},
				label: [],
				smooth: true,
				symbol: 'none',
				lineStyle: {
					width: 3,
					color: ''
				}
			}
		]
	};

	const tooltipText = (params: any, percent = '%'): void | string => {
		let tip = '';
		if (params !== null && params.length > 0) {
			tip += params[0].name + '<br/>';
			if (params.length > 1) {
				for (let i = 0; i < 2; i++) {
					let j = i + 2;
					tip += params[i].marker + `${params[i].seriesName}` + params[j].value + `${percent}<br />`;
				}
			} else {
				tip += params[0].marker + `${params[0].seriesName}` + params[0].value + `${percent}<br />`;
			}
		}
		return tip;
	};
	// cpu图绘制
	performanceData.cpuQueue.map((cpuData: numberData) => {
		option.xAxis.data.push(cpuData.time);
		option.series[0].data.push(cpuData.data);
	});
	option.series[0].lineStyle.color = 'rgba(92, 201, 105, 1)';

	option.series[0].name = 'CPU利用用率:';
	// option.series[0].lintyle.width = 5;
	// option.series[0].lineStyle.color = 'rgba(92, 201, 105, 1)';
	// option.series[1].lineStyle.color = 'rgba(92, 201, 105, 1)';
	// option.series[2].lineStyle.color = 'rgba(92, 201, 105, 1)';
	// option.series[3].lineStyle.color = 'rgba(92, 201, 105, 1)';

	// console.log('option:', option);

	option.color = ['rgba(92, 201, 105, 0.15)'];
	option.tooltip.formatter = function (params: any) {
		return tooltipText(params);
	};
	option && cpuChart.setOption(option);

	// npu图绘制
	option.color = ['rgba(89, 125, 206, 0.15)'];
	option.series[0].name = 'NPU利用用率:';
	option.series[0].data = [];
	performanceData.npuQueue.map((cpuData: numberData) => {
		option.series[0].data.push(cpuData.data);
	});
	option.tooltip.formatter = function (params: any) {
		return tooltipText(params);
	};
	option.series[0].lineStyle.color = 'rgba(89, 125, 206, 1)';

	option && npuChart.setOption(option);

	//  内存图绘制
	option.color = ['rgba(48, 93, 194, 0.15)'];
	option.series[0].data = [];
	performanceData.memoryQueue.map((cpuData: numberData) => {
		option.series[0].data.push(cpuData.data);
	});
	option.series[0].name = '内存利用用率:';
	option.series[0].lineStyle.color = 'rgba(48, 93, 194, 1)';

	option.tooltip.formatter = function (params: any) {
		return tooltipText(params);
	};
	option && memoryChart.setOption(option);

	// network图绘制
	option.color = ['#00A9C3', '#F59700'];
	option.yAxis.axisLabel.formatter = '{value}';
	option.series[0].data = [];
	performanceData.networkQueue.map((networkData: timeDate) => {
		option.series[0].data.push(networkData.data.out.data);
		option.series[1].data.push(networkData.data.in.data);
		option.series[2].data.push(networkData.data.out.value);
		option.series[3].data.push(networkData.data.in.value);
	});
	option.series[0].areaStyle = null;
	option.series[1].areaStyle = null;
	option.series[0].name = '上行流量:';
	option.series[0].lineStyle.color = 'rgba(69, 187, 211, 1)';

	option.series[1].name = '下行流量:';
	option.series[1].lineStyle.color = 'rgba(245, 151, 0, 1)';

	option.grid.x = 70;
	option.tooltip.formatter = function (params: any) {
		return tooltipText(params, '');
	};

	option && networkChart.setOption(option);
};
const getMonitor = async (): Promise<void> => {
	try {
		const { data } = await BoxManageApi.getBoxPerformanceMonitorData(boxSerial.value);
		console.log('getBoxPerformanceMonitorData======:', data);
		if (data) {
			performanceData = data;
			diskData = data?.diskQueue?.data;
			if (data?.diskQueue?.data?.use) {
				diskData.percent = (data?.diskQueue?.data?.use / data.diskQueue?.data?.total) * 100;
			}
			if (data?.cpuQueue) {
				performancePercentData.cpu = data?.cpuQueue?.slice(-1)[0]?.data;
			}
			if (data?.npuQueue) {
				performancePercentData.npu = data?.npuQueue?.slice(-1)[0]?.data;
			}
			if (data?.memoryQueue) {
				performancePercentData.memory = data?.memoryQueue?.slice(-1)[0]?.data;
			}
			if (data?.networkQueue) {
				performancePercentData.network = {
					out: data?.networkQueue?.slice(-1)[0]?.data.out.value,
					in: data?.networkQueue?.slice(-1)[0]?.data.in.value
				};
			}
		}
		draw();
	} catch (error) {
		console.error(error);
	}
};

SocketState.ws.onmessage = (info: { data: string }) => {
	let obj = JSON.parse(info.data);
	if (obj) {
		exceedAuthority(obj);
		if (obj.message === 'AlgorithmServer' && obj.serial === boxSerial.value) {
			console.log(obj);

			performanceData = obj;
			diskData = obj.diskQueue?.data;
			diskData.percent = (obj.diskQueue.data.use / obj.diskQueue.data.total) * 100;
			performancePercentData.cpu = obj.cpuQueue.slice(-1)[0].data;
			performancePercentData.npu = obj.npuQueue.slice(-1)[0].data;
			performancePercentData.memory = obj.memoryQueue.slice(-1)[0].data;
			performancePercentData.network = {
				out: obj.networkQueue.slice(-1)[0].data.out.value,
				in: obj.networkQueue.slice(-1)[0].data.in.value
			};
			draw();
		}
	}
};
const timer = ref<NodeJS.Timeout>();

onMounted(() => {
	id.value = route.query?.id as string;
	boxSerial.value = route.query?.boxSerial as string;
	name.value = route.query?.name as string;

	const setContent = {
		// 设置控制图表大小变量
		width: 540,
		height: 240
	};
	cpuChart = echarts.init(cpu.value as any, undefined, setContent);
	npuChart = echarts.init(npu.value as any, undefined, setContent);
	networkChart = echarts.init(network.value as any, undefined, setContent);
	memoryChart = echarts.init(memory.value as any, undefined, setContent);
	getMonitor();
	draw();
	timer.value = setInterval(() => {
		getMonitor();
	}, 3000);
});

onBeforeUnmount(() => {
	clearTimeout(timer.value);
});
</script>

<style lang="less" scoped>
.boxes-detail-performance {
	width: 1200px;
	height: 100%;
	margin: 0 auto;

	.the-monitor-content {
		box-sizing: border-box;
		width: 100%;
		padding-top: 40px;

		.the-common-title {
			position: relative;
			font-size: 16px;
			font-weight: 700;
			line-height: 24px;
			color: @text01;

			.text {
				display: inline-block;
				margin-left: 8px;
				font-size: 16px;
				font-weight: 700;
				line-height: 24px;
				color: @text01;
			}
			// &::before {
			// 	position: absolute;
			// 	top: 3px;
			// 	left: 0;
			// 	width: 3px;
			// 	height: 18px;
			// 	border-radius: 0 2px 2px 0;
			// 	background: #1868e9;
			// 	content: '';
			// }
		}

		.the-performance-monitor {
			box-sizing: border-box;
			height: 666px;
			margin-top: 24px;
			border: 1px solid @borderColor02;
			border-radius: 4px;
			padding: 12px 20px;
			background: @background02;

			.the-performance-content {
				display: flex;
				height: 600px;
				margin-top: 5px;
				justify-content: space-between;
				flex-wrap: wrap;

				.the-content-child {
					box-sizing: border-box;
					width: 572px;
					height: 292px;
					margin-top: 12px;
					border: 1px solid @mask02;
					border-radius: 4px;
					padding: 12px 16px;
					background-color: #1b253a;

					.the-child-title {
						font-size: 14px;
						font-weight: 700;
						line-height: 22px;
						color: @text02;
					}

					.the-child-network {
						display: flex;

						.the-network-speed {
							display: flex;
							margin-right: 50px;
							align-items: center;

							.speed-out-icon {
								width: 9px;
								height: 9px;
								margin-right: 2px;
								border-radius: 50%;
								background: #00a9c3;
							}

							.speed-in-icon {
								width: 9px;
								height: 9px;
								margin-right: 2px;
								border-radius: 50%;
								background: #f59700;
							}

							.speed-title {
								margin-right: 8px;
								font-size: 12px;
								font-weight: 400;
								line-height: 20px;
								color: @text02;
							}

							.speed-number {
								font-size: 18px;
								font-weight: 700;
								line-height: 26px;
								color: @text01;
							}

							.speed-symbol {
								margin-left: 2px;
								font-size: 12px;
								font-weight: 400;
								line-height: 20px;
								color: @text02;
							}
						}
					}

					.the-child-percent {
						margin: 2px 0 8px;
						font-size: 18px;
						font-weight: 700;
						line-height: 26px;
						color: @text01;

						.the-percent-symbol {
							font-size: 12px;
							font-weight: 400;
							line-height: 20px;
							color: @text02;
						}
					}

					.the-child-chart {
						width: 572px;
						height: 200px;
						background-color: transparent;
					}
				}
			}
		}

		.the-store-information {
			box-sizing: border-box;
			height: 148px;
			border: 1px solid @borderColor01;
			border-radius: 4px;
			padding: 12px 20px 32px;
			background: @background04;

			.the-common-title {
				margin-bottom: 24px;
			}

			.the-information-content {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;

				.information-detail {
					display: flex;
					width: 100%;
					justify-content: space-between;

					.use-status {
						font-size: 14px;
						font-weight: 400;
						line-height: 22px;
						color: @text02;
					}

					.detail-percent {
						font-size: 12px;
						font-weight: 400;
						line-height: 20px;
						color: @text02;

						.detail-percent-current {
							font-size: 16px;
							font-weight: 700;
							line-height: 24px;
							color: @text01;
						}
					}
				}

				::v-deep(.ant-progress-inner) {
					margin-top: 8px;
					border: 1px solid @borderColor01;
					border-radius: 6px;
					background-color: @mask02;

					.ant-progress-bg {
						height: 24px !important;
						border-radius: 6px;
						border-top-right-radius: 0;
						border-bottom-right-radius: 0;
						background-color: @success01;
					}
				}
			}
		}

		.logo {
			width: 196px;
			height: 16px;
			margin-top: 26px;

			img {
				width: 100%;
				height: 100%;
				object-fit: cover;
				margin-bottom: 40px;
			}
		}
	}
}
</style>
